package edu.tomee.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import edu.tomee.db.DatabaseConnection;
import edu.tomee.db.ExpenseInfo;
import edu.tomee.db.UserInfo;

/**
 * Servlet implementation class ExpenseSheetServlet
 */
@WebServlet("/expense")
public class ExpenseSheetServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ExpenseSheetServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    DatabaseConnection db = new DatabaseConnection();
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		UserInfo usrdtls =  (UserInfo) request.getSession().getAttribute("rslt");
		int uid = usrdtls.getUid();
		int totalExpense = 0;
		List<ExpenseInfo> expnsRprt = db.displayExpnsRprt(uid);
		for (ExpenseInfo expenseInfo : expnsRprt) {
			totalExpense = totalExpense + expenseInfo.getPrice();
		}
		request.setAttribute("totalExpense", totalExpense);
		request.setAttribute("expnslist", expnsRprt);
		request.getRequestDispatcher("expense_sheet.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	PrintWriter out = response.getWriter();
	response.setContentType("text/html");
	int totalExpense = 0;
	String date = request.getParameter("dt");
	String item = request.getParameter("itm");
	String price = request.getParameter("pric");
	String expense = request.getParameter("expns");
	HttpSession session = request.getSession();
	UserInfo usrdtls =  (UserInfo) session.getAttribute("rslt");
	int uid = usrdtls.getUid();
	System.out.println("uid "+uid);
	List<ExpenseInfo> expnsRprt = db.displayExpnsRprt(uid);
	for (ExpenseInfo expenseInfo : expnsRprt) {
		int e = expenseInfo.getTexpense();
	}
	for (ExpenseInfo expenseInfo : expnsRprt) {
		 totalExpense = totalExpense + expenseInfo.getPrice();
	}
	request.setAttribute("totalExpense", totalExpense);
	request.setAttribute("expnslist", expnsRprt);
	int entry = db.expenseEntry(uid,date,item,Integer.parseInt(price),Integer.parseInt(expense));
	request.setAttribute("etrystatus", entry);
	request.getRequestDispatcher("expense_sheet.jsp").forward(request, response);
	}

}
